const express = require('express');
const WebSocket = require('ws');
const axios = require('axios');

const app = express();
const port = 3002;

// 创建WebSocket服务器
const wss = new WebSocket.Server({ noServer: true });

wss.on('connection', (ws) => {
  ws.on('message', async (message) => {
    try {
      // 调用DeepSeek API（需要替换实际API_KEY）
      const response = await axios.post('https://api.deepseek.com/v1/chat/completions', {
        model: "deepseek-chat",
        messages: [{ role: "user", content: message.toString() }]
      }, {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer sk-89a0025e4f3942068ac4bd76446655c5`
        }
      });

      ws.send(response.data.choices[0].message.content);
    } catch (error) {
      console.error('AI接口调用失败:', error);
      ws.send('服务暂时不可用，请稍后再试');
    }
  });
});

// HTTP服务器
const server = app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

// 将WebSocket服务绑定到HTTP服务器
server.on('upgrade', (request, socket, head) => {
  wss.handleUpgrade(request, socket, head, (ws) => {
    wss.emit('connection', ws, request);
  });
});
